import React from 'react';
import { Card, Table, Tag, Button, Space, Modal, Form, Input, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

interface VersionRecord {
  id: string;
  version: string;
  description: string;
  releaseDate: string;
  status: 'active' | 'deprecated' | 'beta';
}

const VersionConfig: React.FC = () => {
  const [data, setData] = React.useState<VersionRecord[]>([
    {
      id: '1',
      version: 'v1.0.0',
      description: '初始版本发布',
      releaseDate: '2024-01-15',
      status: 'active'
    },
    {
      id: '2',
      version: 'v1.1.0',
      description: '新增卡片管理功能',
      releaseDate: '2024-02-01',
      status: 'active'
    },
    {
      id: '3',
      version: 'v1.2.0-beta',
      description: '主题系统重构',
      releaseDate: '2024-02-15',
      status: 'beta'
    }
  ]);
  
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [editingRecord, setEditingRecord] = React.useState<VersionRecord | null>(null);
  const [form] = Form.useForm();

  const statusColors = {
    active: 'green',
    deprecated: 'red',
    beta: 'orange'
  };

  const statusLabels = {
    active: '正式版',
    deprecated: '已废弃',
    beta: '测试版'
  };

  const columns: ColumnsType<VersionRecord> = [
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
      sorter: (a, b) => a.version.localeCompare(b.version),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '发布日期',
      dataIndex: 'releaseDate',
      key: 'releaseDate',
      sorter: (a, b) => new Date(a.releaseDate).getTime() - new Date(b.releaseDate).getTime(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: keyof typeof statusColors) => (
        <Tag color={statusColors[status]}>
          {statusLabels[status]}
        </Tag>
      ),
      filters: [
        { text: '正式版', value: 'active' },
        { text: '测试版', value: 'beta' },
        { text: '已废弃', value: 'deprecated' },
      ],
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record: VersionRecord) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个版本记录吗？',
      onOk: () => {
        setData(data.filter(item => item.id !== id));
        message.success('删除成功');
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingRecord) {
        // 编辑
        setData(data.map(item => 
          item.id === editingRecord.id 
            ? { ...item, ...values }
            : item
        ));
        message.success('更新成功');
      } else {
        // 新增
        const newRecord: VersionRecord = {
          id: Date.now().toString(),
          ...values
        };
        setData([...data, newRecord]);
        message.success('添加成功');
      }
      
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title="版本管理" 
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增版本
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingRecord ? '编辑版本' : '新增版本'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item
            label="版本号"
            name="version"
            rules={[
              { required: true, message: '请输入版本号' },
              { pattern: /^v\d+\.\d+\.\d+(-\w+)?$/, message: '版本号格式不正确，如：v1.0.0 或 v1.0.0-beta' }
            ]}
          >
            <Input placeholder="请输入版本号，如：v1.0.0" />
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[{ required: true, message: '请输入版本描述' }]}
          >
            <Input.TextArea 
              placeholder="请输入版本描述" 
              rows={3}
            />
          </Form.Item>

          <Form.Item
            label="发布日期"
            name="releaseDate"
            rules={[{ required: true, message: '请选择发布日期' }]}
          >
            <Input type="date" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <select className="ant-input">
              <option value="active">正式版</option>
              <option value="beta">测试版</option>
              <option value="deprecated">已废弃</option>
            </select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default VersionConfig;